﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Mozlite.Components;
using Mozlite.Data;

namespace Mozlite.WebUI.Mvc4
{
    /// <summary>
    /// 控制器基类。
    /// </summary>
    public abstract class BaseController : Controller
    {
        #region controllers
        /// <summary>
        /// 首页试图。
        /// </summary>
        /// <returns>返回试图结果。</returns>
        public virtual ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 退出登录。
        /// </summary>
        /// <returns>返回试图结果。</returns>
        [AllowAnonymous]
        public virtual ActionResult Logout()
        {
            Users.Logout();
            return Redirect(SiteUrls.DefaultUrl);
        }
        /// <summary>
        /// 登录。
        /// </summary>
        /// <returns>返回试图结果。</returns>
        [AllowAnonymous]
        public virtual ActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 错误信息。
        /// </summary>
        /// <returns>返回试图结果。</returns>
        [AllowAnonymous]
        public virtual ActionResult Message()
        {
            var message = Request.QueryString["msg"];
            if(string.IsNullOrEmpty(message))
                message = Local("Messages_AccessDeny");
            else
            {
                bool isLocal = Request.Get<bool>("local");
                if(isLocal)
                    message = Local(message);
            }
            ViewBag.ErrorMessage = message;
            return View();
        }
        /// <summary>
        /// 登录。
        /// </summary>
        /// <param name="form">表单集合。</param>
        /// <returns>返回试图结果。</returns>
        [HttpPost]
        [AllowAnonymous]
        public virtual ActionResult Login(FormCollection form)
        {
            var validCode = form.Get("ValidCode");
            var userName = form.Get("UserName");
            var password = form.Get("Password");
            var autoLogin = form.Get<bool>("AutoLogin");
            ViewBag.UserName = userName;
            ViewBag.Password = password;
            ViewBag.AutoLogin = autoLogin;
            if (userName == null || password == null)
                return View();
            if (Self.Cookie.IsVCValid(Consts.Login, validCode))
            {
                var status = Users.ValidUser(userName, password);
                if (status == LoginUserStatus.Success)
                {
                    Users.SetLoginStatus();
                    Users.SignIn(autoLogin);
                    string returnUrl = Request.QueryString["ReturnUrl"];
                    if(returnUrl == null)
                        returnUrl = AppContext.Current.User.RoleLevel.RoleDefaultUrl();
                    return Redirect(returnUrl);
                }
                ViewBag.Message = Local(status);
            }
            else {
                ViewBag.Message = Local("ValidCode_Error");
            }
            return View();
        }
        /// <summary>
        /// 验证码。
        /// </summary>
        [AllowAnonymous]
        public virtual ActionResult ValidCode()
        {
            int width = RouteData.Get<int>("width", 50);
            int height = RouteData.Get<int>("height", 20);
            string key = RouteData.Get<string>("key", Consts.Login);
            using (Bitmap bitmap = new Bitmap(width, height))  //图片大小
            {
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    string[] Code = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

                    string validateCode = string.Empty;

                    Random rd = new Random(unchecked((int)DateTime.Now.Ticks));

                    Font font = new Font("Verdana", width / 4, FontStyle.Italic);
                    // 生成随即数
                    for (int i = 0; i < 4; i++)
                    {
                        validateCode += Code[rd.Next(10)];
                    }

                    Pen PenLine = new Pen(Brushes.Red, 1);  //实例化笔刷并设定颜色、大小(画X,Y轴用)
                    graphics.Clear(Color.AliceBlue);    //设定背景颜色
                    graphics.DrawLine(PenLine, 0, rd.Next(80), 90, rd.Next(25));
                    graphics.DrawString(validateCode, font, Brushes.Black, 0, 0);

                    for (int i = 0; i <= 25; i++)            //老乱识别
                    {
                        int RandPixelX = rd.Next(0, width);
                        int RandPixelY = rd.Next(0, height);
                        bitmap.SetPixel(RandPixelX, RandPixelY, Color.Blue);
                    }

                    //将验证嘛保存到Session变量中
                    //System.Web.HttpContext.Current.Session["ValidateCode:" + key] = validateCode;
                    Self.Cookie.SetValidCode(key, validateCode);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif);

                        System.Web.HttpContext.Current.Response.ClearContent();
                        System.Web.HttpContext.Current.Response.ContentType = "image/png";
                        System.Web.HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray());   //将图像输出的页面   
                    }

                    graphics.Dispose();//释放资源   
                    bitmap.Dispose();//释放资源
                }
            }
            return Content(null);
        }
        /// <summary>
        /// 服务端脚本。
        /// </summary>
        /// <returns>返回脚步内容结果。</returns>
        [AllowAnonymous]
        public virtual ActionResult Resourcejs() {
            var sb = new StringBuilder();
            sb.AppendFormat("var res = {{ key:'{0}'", Current.CultureName);
            AppendResourceJSON(sb);
            sb.Append("};");
            return Content(sb.ToString());
        }
        /// <summary>
        /// 附加资源JSON，每个附加的节点必须以“,”开头。
        /// </summary>
        /// <param name="sb">JSON存储对象。</param>
        protected virtual void AppendResourceJSON(StringBuilder sb) { 
        
        }
        #endregion

        #region views
        private string action;
        /// <summary>
        /// 获取当前请求的Action名称。
        /// </summary>
        public string Action
        {
            get
            {
                if (action == null)
                    action = RouteData.Get<string>("action");
                return action;
            }
        }

        private string controller;
        /// <summary>
        /// 获取当前请求的Controller名称。
        /// </summary>
        public string Controller
        {
            get
            {
                if (controller == null)
                    controller = RouteData.Get<string>("controller");
                return controller;
            }
        }

        /// <summary>
        /// 当前模板。
        /// </summary>
        public string Theme
        {
            get
            {
                return Current.Theme;
            }
        }
        /// <summary>
        /// 获取模板下的URL地址。
        /// </summary>
        /// <param name="args">URL组合。</param>
        /// <returns>返回模板下的URL地址。</returns>
        public string GetThemeUrl(params object[] args) {
            return Cores.GetUrl("App_Templates", this.Theme, args.Join("/"));
        }
        /// <summary>
        /// 获取模板下的物理路径。
        /// </summary>
        /// <param name="args">路径组合。</param>
        /// <returns>返回模板下的物理路径。</returns>
        public string GetThemePath(params object[] args)
        {
            return Cores.GetPath("App_Templates", this.Theme, args.Join("\\"));
        }
        #endregion

        #region pager
        /// <summary>
        /// 获取排序规则。
        /// </summary>
        /// <param name="defaultValue">默认排序。</param>
        /// <returns>返回排序规则。</returns>
        protected virtual string OrderBy(string defaultValue)
        {
            return defaultValue;
        }
        private int pageIndex = -1;
        /// <summary>
        /// 页码，从1开始。
        /// </summary>
        public int PageIndex
        {
            get
            {
                if(pageIndex == -1)
                {
                    pageIndex = RouteData.Get<int>("Page", Current.PageIndex);
                    if(pageIndex < 1)
                        pageIndex = 1;
                }
                return pageIndex;
            }
        }

        private int pageSize = 0;
        /// <summary>
        /// 每页显示的记录数。
        /// </summary>
        public int PageSize
        {
            get
            {
                if(pageSize == 0)
                {
                    pageSize = RouteData.Get<int>("Page", Current.PageSize);
                }
                return pageSize;
            }
            set
            {
                pageSize = value;
                Current.PageSize = value;
            }
        }
        #endregion

        #region resources
        /// <summary>
        /// 获取当前语言资源字符串。
        /// </summary>
        /// <param name="key">资源键对象。</param>
        /// <returns>返回资源字符串。</returns>
        public virtual string Local(object key)
        {
            return Cores.GetGlobalResourceByKey(key);
        }

        /// <summary>
        /// 获取当前语言资源字符串。
        /// </summary>
        /// <param name="key">资源键对象。</param>
        /// <param name="args">格式化参数。</param>
        /// <returns>返回格式化后的资源字符串。</returns>
        public virtual string Local(object key, params object[] args)
        {
            return Cores.GetGlobalResourceByKey(key).FormatWith(args);
        }

        private void ShowMessage(string key, string message, params object[] args)
        {
            ViewBag.Status = key;
            ViewBag.Message = message.FormatWith(args);
        }
        /// <summary>
        /// 显示信息。
        /// </summary>
        /// <param name="message">信息字符串。</param>
        /// <param name="args">参数。</param>
        protected virtual void ShowInformation(string message, params object[] args)
        {
            ShowMessage("info", message, args);
        }
        /// <summary>
        /// 显示成功信息。
        /// </summary>
        /// <param name="message">信息字符串。</param>
        /// <param name="args">参数。</param>
        protected virtual void ShowSuccess(string message, params object[] args)
        {
            ShowMessage("success", message, args);
        }
        /// <summary>
        /// 显示错误信息。
        /// </summary>
        /// <param name="message">信息字符串。</param>
        /// <param name="args">参数。</param>
        protected virtual void ShowError(string message, params object[] args)
        {
            ShowMessage("error", message, args);
        }
        /// <summary>
        /// 显示资源信息。
        /// </summary>
        /// <param name="message">信息字符串。</param>
        /// <param name="args">参数。</param>
        protected virtual void ShowLocalInformation(object key, params object[] args)
        {
            ShowMessage("info", Local(key, args));
        }
        /// <summary>
        /// 显示成功资源信息。
        /// </summary>
        /// <param name="message">信息字符串。</param>
        /// <param name="args">参数。</param>
        protected virtual void ShowLocalSuccess(object key, params object[] args)
        {
            ShowMessage("success", Local(key, args));
        }
        /// <summary>
        /// 显示错误资源信息。
        /// </summary>
        /// <param name="message">信息字符串。</param>
        /// <param name="args">参数。</param>
        protected virtual void ShowLocalError(object key, params object[] args)
        {
            ShowMessage("error", Local(key, args));
        }
        /// <summary>
        /// 资源名称区域语言。
        /// </summary>
        protected string CultureName {
            get {
                return Current.CultureName;
            }
        }
        #endregion

        #region common
        private User user;
        /// <summary>
        /// 当前登录实例对象。
        /// </summary>
        public User Self
        {
            get
            {
                if (user == null)
                    user = AppContext.Current.User;
                return user;
            }
        }

        private AppContext current;
        /// <summary>
        /// 获取当前应用程序上下文实例。
        /// </summary>
        public AppContext Current
        {
            get
            {
                if(current == null)
                    current = AppContext.Current;
                return current;
            }
        }

        private GlobalSettings gSettings;
        /// <summary>
        /// 获取全局设置。
        /// </summary>
        public GlobalSettings GSettings {
            get {
                if(gSettings == null)
                    gSettings = GlobalSettings.Current;
                return gSettings;
            }
        }

        private SiteSettings siteSettings;
        /// <summary>
        /// 获取网站设置。
        /// </summary>
        public SiteSettings SiteSettings
        {
            get {
                if(siteSettings == null)
                    siteSettings = SiteSettings.Current;
                return siteSettings;
            }
        }
        #endregion
    }
}
